<template>
  <div class="tablePageWarp" style="height: calc(100vh - 260px)">
    <div style="width:600px">
      <a-spin :spinning="patternLoading">
        <a-radio-group buttonStyle="solid" v-model="modelIDriveUrlAttr" :disabled="!$hasPermission($managePerms.adasEcuConfig.operate)"
                       style="margin-bottom: 8px;padding-right:25px;">
          <a-radio-button v-for="item in patterns" :value="item.value" @click.stop.prevent="changePattern(item)">
            {{item.name}}
          </a-radio-button>
        </a-radio-group>
      </a-spin>
    </div>
<!--    <div :style="{opacity: modelIDriveUrlAttr==='part' ? 1 : 1}" class="h100">-->
      <div class="commonSelectWidth">
        <a-row :gutter="[16,0]">
          <a-col :md="4" :sm="24">
              <a-input v-model="queryParam.vin" placeholder="VIN"/>
          </a-col>
          <a-col :md="12" :sm="24">
            <div class="searchBtns" style="">
              <auth-button type="primary" :auth="$managePerms.adasEcuConfig.view" @click="refreshData(true)">
                <i class="iconfont icon-chazhao"></i>
                {{ $t('inquiry') }}
              </auth-button>
              <a-button @click="batchSwitch(true, 'batchOpenLoading')" :loading="batchOpenLoading"
                        :disabled="modelIDriveUrlAttr!=='part' || !$hasPermission($managePerms.adasEcuConfig.operate)">批量开启</a-button>
              <a-button @click="batchSwitch(false, 'batchCloseLoading')" :loading="batchCloseLoading"
                        :disabled="modelIDriveUrlAttr!=='part' || !$hasPermission($managePerms.adasEcuConfig.operate)">批量取消</a-button>
            </div>
          </a-col>
        </a-row>
      </div>
      <s-table ref="table"
               class="h100"
               size="default"
               rowKey="vin"
               :columns="cols"
               :data="loadData"
               :addLoading="true"
               :row-selection="{ selections:true,selectedRowKeys:selectedRowKeys, onChange: onTableSelectChange }"
               :getPopupContainer="$commonFun.getPopupContainer">
        <template #idriveWhiteList="text,record">
          <a-switch :checked="text === 1" @change="(e) => switchVehicle(e, record)" :loading="record.loading"
                    :disabled="modelIDriveUrlAttr!=='part' || !$hasPermission($managePerms.adasEcuConfig.operate)"/>
        </template>
      </s-table>
<!--    </div>-->
  </div>
</template>
<script>
  import i18n from "@/lang";
  import api from "@api/modules/system/adasEcuConfig";

  export default {
    name: 'adasEcuConfigList',
    props: {
      modelId: {
        type: String,
        required: true
      },
      /**
       * 1：正式车辆
       * 2：测试车辆
       */
      vehicleType: {
        type: Number,
        required: true
      },
      updateCallback: {
        type: Function,
        default: () => {}
      }
    },
    data() {
      var vm = this;
      return {
        modelIDriveUrlAttr: '',
        patterns: [
          {
            name: '部分生效',
            value: 'part'
          },
          {
            name: '全部生效',
            value: 'all'
          },
          {
            name: '全部取消',
            value: 'none'
          },
        ],
        selectedRowKeys: [],
        queryParam: {
          vehicleType : vm.vehicleType
        },
        patternLoading: false,
        batchOpenLoading: false,
        batchCloseLoading: false,
        cols: [
          {
            title: i18n.t('VIN'),
            dataIndex: 'vin',
            width: 200,
          },
          {
            title: i18n.t('款型名称'),
            dataIndex: 'modelStyleVo.name',
            width: 130,
          },
          {
            title: i18n.t('生产车型'),
            dataIndex: 'productionModel',
            width: 200,
          },
          {
            title: i18n.t('生产车系'),
            dataIndex: 'productionSeries',
            width: 200,
          },
          {
            title: i18n.t('iccId'),
            dataIndex: 'iccid',
            width: 200,
          },
          {
            title: i18n.t('车辆类型'),
            dataIndex: 'vehicleType',
            width: 130,
            customRender: (text, record, index) => {
              if (text === 1) {
                return '正式车辆'
              } else if (text === 2) {
                return '测试车辆'
              } else if (text === 3) {
                return '种子车辆'
              } else {
                return ''
              }
              // return vm.$store.getters.getDictCodeObj('vehicleTypeDictCode')[text] || text;
            },
          },
          {
            title: i18n.t('校验开关'),
            dataIndex: 'idriveWhiteList',
            width: 130,
            fixed:'right',
            scopedSlots: {customRender: 'idriveWhiteList'}
          },
        ]
      }
    },
    created() {
      this.patternLoading = true
      api.getVehiclePattern(this.modelId).then(res => {
        if (this.vehicleType === 1) {
          this.modelIDriveUrlAttr = res.data.modelIDriveUrlAttr;
        } else {
          this.modelIDriveUrlAttr = res.data.testModelIDriveUrlAttr;
        }
        this.patternLoading = false;
      })
      this.$store.dispatch('getVehicleTypeDictCodeData');
    },
    methods: {
      loadData(page) {
        if (!this.modelId) {
          return null;
        }
        return api.getVehicleConfig({...page, ...this.queryParam, modelIds: [this.modelId]});
      },
      refreshData(isToFirstPage = false) {
        const vm = this
        vm.$nextTick(() => {
          this.$refs.table.refresh(isToFirstPage)
        })
      },
      switchVehicle(enabled, record) {
        let vm = this;
        this.$confirm({
          title: vm.$t('车辆配置'),
          content: enabled ? '您确定要开启吗？开启后，车辆将会在下载升级文件前校验下载地址的域名'
            : '您确定要关闭校验吗？关闭后，车辆在下载升级文件前不再校验下载地址的域名',
          onOk() {
            record.loading = true;
            api.saveVehicleConfig(record.modelId, [{
              vin: record.vin,
              idrive: enabled ? 1 : 0
            }]).then(() => {
              vm.refreshData(true);
              vm.updateCallback();
            }).finally(()=>{
              record.loading = false;
            });
          },
          onCancel() {
          }
        })
      },
      batchSwitch(enabled, loading) {
        let vm = this;
        this.$confirm({
          title: vm.$t('车辆配置'),
          content: enabled ? '您确定要开启选中车辆的校验吗？开启后，车辆将会在下载升级文件前校验下载地址的域名' :
            '您确定要关闭选中车辆的校验吗？关闭后，车辆在下载升级文件前不再校验下载地址的域名',
          onOk() {
            vm[loading] = true;
            api.saveVehicleConfig(vm.modelId, vm.selectedRowKeys.map(value => {
              return {
                vin: value,
                idrive: enabled ? 1 : 0
              }
            })).then(() => {
              vm.selectedRowKeys = [];
              vm.refreshData(true);
              vm.updateCallback();
            }).finally(() => vm[loading] = false);
          },
          onCancel() {
          }
        })
      },
      changePattern(pattern) {
        this.selectedRowKeys=[];
        let vm = this;
        this.$confirm({
          title: vm.$t('车辆配置'),
          content: '您确定要更改为'+(pattern?.name)+'吗',
          onOk() {
            vm.modelIDriveUrlAttr = pattern?.value;
            let method = vm.vehicleType === 1 ? api.saveVehiclePattern : api.saveTestVehiclePattern;
            method(vm.modelId, {modelIDriveUrlAttr: vm.modelIDriveUrlAttr,testModelIDriveUrlAttr: vm.modelIDriveUrlAttr}).then(() => {
              vm.selectedRowKeys = [];
              // vm.refreshData(false);
              vm.updateCallback();
            });
          },
          onCancel() {
          }
        })
        return false;
      },
      onTableSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys;
      },
    }
  }
</script>